﻿// NFakeMail - A fake SMTP Server for software testing.
// 
// Copyright (C) 2010, João Angelo
// 
// This file is part of NFakeMail.
//
// NFakeMail is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
// 
// NFakeMail is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with NFakeMail; if not, see <http://www.gnu.org/licenses/>.

namespace NFakeMail
{
    using System;
    using System.Globalization;
    using System.IO;

    /// <summary>
    /// Represents an output data repository that writes the received data to the file system.
    /// </summary>
    /// <author> jmangelo </author>
    /// <history>
    /// ______________________________________________________________________________________
    /// History :
    /// 20100816 [+] jmangelo     Initial version
    /// ______________________________________________________________________________________
    /// </history>
    public sealed class FileSystemOutputSink : OutputSink
    {
        public FileSystemOutputSink(string repositoryPath)
        {
            if (repositoryPath == null)
            {
                throw new ArgumentNullException("repositoryPath");
            }

            if (String.IsNullOrWhiteSpace(repositoryPath))
            {
                throw new ArgumentException(
                    "Path cannot be an empty or whitespace only string.", 
                    "repositoryPath");
            }

            if (!Directory.Exists(repositoryPath))
            {
                Directory.CreateDirectory(repositoryPath);
            }

            this.MessageRepositoryPath = repositoryPath;
        }

        public string MessageRepositoryPath { get; private set; }

        public override void Write(string text)
        {
            // Does nothing - This appender just saves full MIME messages to the file system
        }

        public override void Write(FakeMailMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            string mimeMessageFileName = String.Format(
                CultureInfo.InvariantCulture,
                "{0}-{1}.eml", 
                DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture),
                Path.GetRandomFileName());

            File.WriteAllText(
                Path.Combine(this.MessageRepositoryPath, mimeMessageFileName), 
                message.MimeMessage);
        }
    }
}
